<template>
  <div class="app-container">
    <el-card shadow="hover">
      <el-form ref="form" size="mini" :model="listQuery" label-width="100px">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="4">
            <el-form-item prop="lsh" :label="$t('drugitemmaintenance.yppmh')+':'">
              <el-input clearable :placeholder="'请输入'+$t('drugitemmaintenance.yppmh')" v-model="listQuery.yppmh"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="4">
            <el-form-item prop="name" :label="$t('drugInformation.name')+':'">
              <el-input clearable :placeholder="'请输入'+$t('drugInformation.name')" v-model="listQuery.name"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="4">
            <el-form-item prop="jx" :label="$t('drugInformation.jx')+':'">
              <el-input clearable :placeholder="'请输入'+$t('drugInformation.jx')" v-model="listQuery.jx"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="4">
            <el-form-item prop="specification"
                          :label="$t('drugInformation.specification')+':'">
              <el-input clearable :placeholder="'请输入'+$t('drugInformation.specification')"
                        v-model="listQuery.specification"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="4">
            <el-form-item prop="unit" :label="$t('drugInformation.unit')+':'">
              <el-input clearable :placeholder="'请输入'+$t('drugInformation.unit')" v-model="listQuery.unit"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="4">
            <el-form-item prop="zhxs" :label="$t('drugInformation.zhxs')+':'">
              <el-input clearable :placeholder="'请输入'+$t('drugInformation.zhxs')" v-model="listQuery.zhxs"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="4">
            <el-form-item prop="yptype" :label="$t('drugInformation.yptype')+':'">
              <el-select v-model="listQuery.yptype" :placeholder="'请选择'+$t('drugInformation.yptype')">
                <el-option label="全部" value="-1"/>
                <template v-for="(item,index) of dictData.yptype">
                  <el-option :key="item.id" :label="item.dictLabel" :value="item.dictValue"/>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="4">
            <el-form-item prop="ypzt" :label="$t('drugitemmaintenance.ypzt')+':'">
              <el-select v-model="listQuery.ypzt" :placeholder="'请选择'+$t('drugitemmaintenance.ypzt')">
                <el-option label="全部" value="-1"/>
                <template v-for="(item,index) of dictData.ypjyztType">
                  <el-option :key="item.id" :label="item.dictLabel" :value="item.dictValue"/>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row type="flex" justify="center">
          <el-col :xs="12" :sm="9" :md="6" :lg="3" :xl="3">
            <el-button class="pan-btn green-btn" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                       @click="getList">
              查询
            </el-button>
          </el-col>
          <el-col :xs="12" :sm="9" :md="6" :lg="3" :xl="3">
            <el-button class="pan-btn yellow-btn" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                       @click="reset">
              清空
            </el-button>
          </el-col>
          <el-col :xs="12" :sm="9" :md="6" :lg="3" :xl="3">
            <el-button :loading="downloadLoading" style="margin-left: 10px;" class="pan-btn blue-btn" type="primary"
                       icon="el-icon-top" @click="handleDownload">
              {{ $t('table.export') }}
            </el-button>
          </el-col>
        </el-row>

      </el-form>
    </el-card>

    <br/>

    <el-card shadow="hover">
      <el-row type="flex" justify="space-between">
        <el-col>
          <el-row type="flex" justify="center">
            <el-col>
              <el-button class="pan-btn green-btn" type="primary" icon="el-icon-edit"
                         @click="handleCreate">
                {{ $t('drugInformation.adddrugInformation') }}
              </el-button>
            </el-col>
            <el-col>
              <el-button :loading="downloadLoading" class="pan-btn light-blue-btn" type="primary" icon="el-icon-bottom"
              >
                {{ $t('table.import') }}
              </el-button>
            </el-col>
            <el-col>
              <el-button :loading="downloadLoading" class="pan-btn light-blue-btn" type="primary" icon="el-icon-bottom"
                         @click="handleBatchDel">
                {{isMultiple?"取消选择":"批量删除"}}
              </el-button>
            </el-col>
            <el-col v-if="isMultiple">
              <el-button :loading="downloadLoading" class="pan-btn light-blue-btn" type="primary" icon="el-icon-bottom"
                         @click="handleAffirmDel">
                确认删除
              </el-button>
            </el-col>
          </el-row>
        </el-col>

        <el-col :span="12">
          <pagination style="margin: 0;padding: 0" v-show="pageInfo.total > 0" :total="pageInfo.total"
                      :page.sync="pageInfo.page"
                      :limit.sync="pageInfo.size"
                      @pagination="this.getList"/>
        </el-col>
      </el-row>
      <br/>
      <el-table
        :data="tableData"
        ref="multipleTable"
        v-loading="listLoading"
        border
        stripe
        size="mini"
        @selection-change="handleSelectionChange"
        style="width: 100%">
        <el-table-column v-if="isMultiple"
                         type="selection"
                         width="55">
        </el-table-column>

        <el-table-column :label="$t('drugitemmaintenance.yppmh')" align="center">
          <template slot-scope="{row}">
            <span>{{ row.yppmh }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('drugInformation.name')" align="center">
          <template slot-scope="{row}">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('drugInformation.jx')" align="center">
          <template slot-scope="{row}">
            <span>{{ row.jx }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('drugInformation.specification')" align="center">
          <template slot-scope="{row}">
            <span>{{ row.specification }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('drugInformation.unit')" align="center">
          <template slot-scope="{row}">
            <span>{{ row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('drugInformation.zhxs')" align="center">
          <template slot-scope="{row}">
            <span>{{ row.zhxs }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('drugInformation.yptype')" align="center">
          <template slot-scope="{row}">
            <span>{{ findDictLable(dictData.yptype,row.yptype) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('drugitemmaintenance.ypzt')" align="center">
          <template slot-scope="{row}">
            <span>{{ findDictLable(dictData.ypjyztType,row.ypzt) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" align="center" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary" class="success" size="mini" @click="handleUpdate(row)">
              {{ $t('table.edit') }}
            </el-button>
            <el-button size="mini" class="danger" type="danger"
                       @click="handleDelete(row,$index)">
              {{ $t('table.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-row type="flex" :gutter="10">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="top">
          <el-col v-if="dialogStatus!=='create'" :xs="24" :sm="24" :md="12" :lg="8" :xl="18">
            <el-form-item :label="$t('drugitemmaintenance.yppmh')"
                          prop="yppmh">
              <el-input :disabled="true" v-model="temp.yppmh"/>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="18">
            <el-form-item :label="$t('drugInformation.name')"
                          prop="name">
              <el-input v-model="temp.name" :placeholder="'请输入'+$t('drugInformation.name')"/>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="18">
            <el-form-item :label="$t('drugInformation.jx')"
                          prop="jx">
              <el-input v-model="temp.jx" :placeholder="'请输入'+$t('drugInformation.jx')"/>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="18">
            <el-form-item :label="$t('drugInformation.specification')"
                          prop="jx">
              <el-input v-model="temp.specification" :placeholder="'请输入'+$t('drugInformation.specification')"/>
            </el-form-item>
          </el-col>


          <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="18">
            <el-form-item :label="$t('drugInformation.unit')"
                          prop="unit">
              <el-input v-model="temp.unit" :placeholder="'请输入'+$t('drugInformation.unit')"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="18">
            <el-form-item :label="$t('drugInformation.zhxs')"
                          prop="zhxs">
              <el-input v-model="temp.zhxs" :placeholder="'请输入'+$t('drugInformation.zhxs')"/>
            </el-form-item>
          </el-col>


          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="4">
            <el-form-item prop="yptype" :label="$t('drugInformation.yptype')+':'">
              <el-select v-model="temp.yptype" :placeholder="'请选择'+$t('drugInformation.yptype')">
                <template v-for="(item,index) of dictData.yptype">
                  <el-option :key="item.id" :label="item.dictLabel" :value="item.dictValue"/>
                </template>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="18">
            <el-form-item :required="true" prop="ypzt" :label="$t('drugitemmaintenance.ypzt')">
              <el-select v-model="temp.ypzt" :placeholder="'请选择'+$t('drugitemmaintenance.ypzt')">
                <template v-for="(item,index) of dictData.ypjyztType">
                  <el-option :key="item.id" :label="item.dictLabel" :value="item.dictValue"/>
                </template>
              </el-select>
            </el-form-item>
          </el-col>

        </el-form>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  import {getYppmbList, save, update, del, delList} from "@/api/jdgl/yppmgl"
  import {getDicts} from "@/api/system/dict/data"

  export default {
    name: "yppmgl",
    components: {Pagination},
    data() {
      let diyRule = {
        phoneRule: (rule, value, callback) => {
          let regExp = /^1((3[\d])|(4[5,6,7,9])|(5[0-3,5-9])|(6[5-7])|(7[0-8])|(8[\d])|(9[1,8,9]))\d{8}$/;
          if (regExp.test(value) === false) {
            callback(new Error('电话号码格式不正确'));
          } else {
            callback();
          }
        },
        emailRule: (rule, value, callback) => {
          if (value !== '' && undefined !== value) {
            let regExp = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
            if (regExp.test(value) === false) {
              callback(new Error('邮箱格式不正确'));
            } else {
              callback();
            }
          } else {
            callback();
          }
        }
      }
      return {
        innerVisible: false,
        listLoading: true,
        downloadLoading: false,
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {
          pmid: null,
          ypzt: null,
          yppmh: null,
          name: null,
          jx: null,
          specification: null,
          unit: null,
          zhxs: null,
          yptype: null,
        },
        rules: {
          name: [{required: true, message: '名字不能为空', trigger: 'blur'}],
          contacts: [{required: true, message: '联系人不能为空', trigger: 'blur'}],
          phone: [{required: true, message: '联系电话不能为空', trigger: 'blur'},
            // {validator: diyRule.phoneRule, trigger: 'blur'}
          ],
          //yzbm: [{type: 'number', message: '邮政编码必须为数字值', trigger: "blur"}],
          email: [{validator: diyRule.emailRule, trigger: 'blur'}]
        },
        textMap: {
          update: 'Edit',
          create: 'Create'
        },
        pageInfo: {
          total: 1,
          page: 1,
          size: 10,
        },
        tableData: [],
        listQuery: {
          ypzt: null,
          yppmh: null,
          name: null,
          jx: null,
          specification: null,
          unit: null,
          zhxs: null,
          yptype: null,
        },
        dictData: {
          ypjyztType: [],
          yptype: [],
          zlcc: []
        },
        isMultiple: false,
        multipleSelection: [], //table选择的行
      }
    },
    created() {
      this.getList();
      this.initDictData();
    },
    methods: {
      initDictData() {
        getDicts("ypjyzt_type").then(res => {
          this.dictData.ypjyztType = res.data;
        }).catch(err => {
          console.log(err);
        })

        getDicts("yp_type").then(res => {
          this.dictData.yptype = res.data;
        }).catch(err => {
          console.log(err);
        })

        getDicts("zlcc_type").then(res => {
          this.dictData.zlcc = res.data;
        }).catch(err => {
          console.log(err);
        })

      },
      getList() {
        this.listLoading = true;
        getYppmbList({...this.pageInfo, ...this.listQuery}).then(res => {
          if (res.code === 200) {
            this.tableData = res.data.rows;
            this.pageInfo.total = res.data.total;
          }
        }).catch(err => {
          console.log(err);
        }).finally(() => {
          this.listLoading = false;
        })
      },
      reset() {
        this.listQuery.price2 = null;
        this.$refs['form'].resetFields()
      },
      dataFormat: function (row, column, cellValue) {
        if (undefined === cellValue || cellValue === "") {
          return "111";
        }
      },
      resetTemp() {
        this.temp = {
          pmid: null,
          ypzt: null,
          yppmh: null,
          name: null,
          jx: null,
          specification: null,
          unit: null,
          zhxs: null,
          yptype: null,
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.author = this.$store.state.user.name;
            save(this.temp).then((res) => {
                this.temp.yppmh = res.data
                this.tableData.unshift(this.temp)
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
              }
            )
          }
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = Object.keys(this.temp)
          const filterVal = Object.keys(this.temp)
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '药品品目集合'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal) {
        return this.tableData.map(v => filterVal.map(j => {
          if (j === 'createTime') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        console.log(this.temp);
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            update(tempData).then(() => {
              const index = this.tableData.findIndex(v => v.pmid === this.temp.pmid)
              this.tableData.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row, index) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log(row.pmid);
          del(row && row.pmid).then(() => {
            this.tableData.splice(index, 1)
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          }).catch(err => {
            console.log(err);
          })
        }).catch(() => {

        });
      },
      handleAffirmDel() {
        if (this.multipleSelection.length !== 0) {
          this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let ids = []
            this.multipleSelection.forEach(i => {
              ids.push({'pmid': i.pmid})
            })
            delList(ids).then(() => {
              ids.forEach(i => {
                this.tableData.splice(this.tableData.findIndex(v => v.id === i.id), 1)
              })
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            }).catch(err => {
              console.log(err);
            }).finally(() => {
              this.$refs.multipleTable.clearSelection()
            })
          })
        } else {
          this.$notify({
            title: '失败',
            message: '请选择一条数据',
            type: 'error',
            duration: 2000
          })
        }
      },
      handleBatchDel() {
        this.isMultiple = !this.isMultiple
        if (!this.isMultiple) {
          this.$refs.multipleTable.clearSelection()
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      }
    }
  }
</script>
